<?php
/**
 * 
 * swxCI. 
 * 
 * An effort to bring together the excellent CodeIgniter & SWX.
 * 
 * The swxCI code is based on the CodeIgniter front controller code, 
 * the SWX gateway code. 
 * 
 * CodeIgniter is Copyright (c) 2008, EllisLab, Inc.
 * See codeigniter_license.txt for full license.
 *
 * SWX is licensed under MIT License & Creative Commons GNU GPL License.
 * See http://www.swxformat.org/license.php for further info.
 * 
 * swxCI is released as is, under Creative Commons Attribution 3.0 Unported License
 * Feel free to modify & adapt but respect the existing licenses for its parts.
 * 
 * swxCI is developed by the SWX Format Development team: 
 * http://code.google.com/p/swx-format/
 */

require("swxCI_config.php");

if (strpos($system_folder, '/') === FALSE)
{
	if (function_exists('realpath') AND @realpath(dirname(__FILE__)) !== FALSE)
	{
		$system_folder = realpath(dirname(__FILE__)).'/'.$system_folder;
	}
}
else
{
	// Swap directory separators to Unix style for consistency
	$system_folder = str_replace("\\", "/", $system_folder); 
}

define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION));
define('FCPATH', __FILE__);
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('BASEPATH', $system_folder.'/');

if (is_dir($application_folder))
{
	define('APPPATH', $application_folder.'/');
}
else
{
	if ($application_folder == '')
	{
		$application_folder = 'application';
	}

	define('APPPATH', BASEPATH.$application_folder.'/');
}


if ($use_services_folder)
	$swx_base = $swx_folder . "/services/";
else
	$swx_base = APPPATH.'controllers/';


define('CI_VERSION',	'1.7.0');	

require(BASEPATH.'codeigniter/Common'.EXT);
require(BASEPATH.'codeigniter/Compat'.EXT);
require(APPPATH.'config/constants'.EXT);


set_error_handler('_exception_handler');
set_magic_quotes_runtime(0); // Kill magic quotes

$BM =& load_class('Benchmark');
$BM->mark('total_execution_time_start');
$BM->mark('loading_time_base_classes_start');


$EXT =& load_class('Hooks');

$EXT->_call_hook('pre_system');


$CFG =& load_class('Config');



if (floor(phpversion()) < 5)
{
	load_class('Loader', FALSE);
	require(BASEPATH.'codeigniter/Base4'.EXT);
}
else
{
	require(BASEPATH.'codeigniter/Base5'.EXT);
}

// Load the base controller class
load_class('Controller', FALSE);

/** Check amf requests for the service explorer **/
if (isset($_GET['amf']))
{
	// Trick the Router class to believe it's a valid request. Router is autoloaded by Controller in CI 1.7.0
	@include(APPPATH.'config/routes'.EXT);
	unset($_GET['amf']);
	$_GET[$route['default_controller']] = true;
	
	define("PRODUCTION_SERVER", false);
	include $swx_folder."/globals.php";
	include $swx_folder."/core/amf/app/Gateway.php";
	$gateway = new Gateway();
	$gateway->setClassPath($swx_base);
	$gateway->setClassMappingsPath($swx_folder . '/' . $voPath); 
	$gateway->setCharsetHandler("utf8_decode", "ISO-8859-1", "ISO-8859-1");
	$gateway->setErrorHandling(E_ALL ^ E_NOTICE);
	if(PRODUCTION_SERVER)
		$gateway->disableDebug();
	$gateway->enableGzipCompression(25*1024);
	$gateway->service();
	exit();
}


// Load Swx config
require($swx_folder.'/swx_config.php');
define("SWX_SERVICESPATH",$servicesPath);
define("SWX_COMPRESSIONLEVEL",$compressionLevel);

// Load Swx utility library
require('swxCI_lib'.EXT);



$format = getParam("format");
if ($format!==null)
	$defaultFormat = $format;

define("SWX_DEFAULTFORMAT",$defaultFormat);	
	
if ($defaultFormat=='as2')
	require($swx_folder.'/SwxAssembler'.EXT);
else
	require($swx_folder.'/SwxAssembler3'.EXT);

set_error_handler('_exception_handlerCI');

// Get SWX Parameters
$class = getParam('serviceClass');
$method = getParam('method');

if ( $class === null || $class=='undefined' || $method === null || $method == 'undefined')
{
	show_errorCI('You must specify a serviceClass & method for the request.');
}

// Load the swx controller
if ( ! file_exists($swx_base.$class.EXT))
{
	show_errorCI('Unable to load your swx service ('.$swx_base.$class.EXT.').  Please make sure your serviceClass, method & path are valid.');
}

require($swx_base.$class.EXT);

	
$args = getParam('args');
	
if ($args!=null)
{
	$args = stripslashes($args);
	// Massage special characters back (is there a better
	// way to do this?)
	$args = str_replace('\\t', '\t', $args);
	$args = str_replace('\\n', '\n', $args);
	$args = str_replace("\\'", "'", $args);	
	$args = str_replace('null', 'NULL', $args);
	
	include_once($swx_folder.'/core/shared/util/JSON.php');
	$j = new Services_JSON();
	$args = $j->decode($args);	
}
else
{
	$args = array();
}


$BM->mark('loading_time_base_classes_end');

if ( ! class_exists($class)
	OR $method == 'controller'
	OR strncmp($method, '_', 1) == 0
	OR in_array(strtolower($method), array_map('strtolower', get_class_methods('Controller')))
	)
{
	show_errorCI("Invalid $class/$method");
}

$EXT->_call_hook('pre_controller');

$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');

/* TODO: Haven't figured out yet why but instanciating the class seems to kill $method & $args. Ah well, back it up. */
$m = $method;
$a = $args;



$CI = new $class();

$EXT->_call_hook('post_controller_constructor');


if ( ! in_array(strtolower($m), array_map('strtolower', get_class_methods($CI))))
{
	show_errorCI("Invalid $class/$m");
}

$ret = call_user_func_array(array(&$CI, $m), $a);

$BM->mark('controller_execution_time_( '.$class.' / '.$m.' )_end');

$EXT->_call_hook('post_controller');

$EXT->_call_hook('post_system');

if (class_exists('CI_DB') AND isset($CI->db))
{
	$CI->db->close();
}

send_result($ret);

/* End of file swxCI.php */
